package trading_strategy.events;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: gderoujoux
 * Date: 6 mai 2010
 * Time: 12:29:49
 * To change this template use File | Settings | File Templates.
 */
public class EventManager {
    static final EventManager instance = new EventManager();
    final Map<String, EventDispatcher> dispatchers = Collections.synchronizedMap(new HashMap<String, EventDispatcher>());
    final Collection<EventProvider> providers = Collections.synchronizedCollection(new HashSet<EventProvider>());
    public static final String REPLAY_DISPATCHER = "ReplayDispatcher";

    public static EventManager getInstance() {
        return instance;
    }

    public EventDispatcher getDispatcher(String name) {
        name = REPLAY_DISPATCHER;
        synchronized (dispatchers) {
            EventDispatcher eventDispatcher = dispatchers.get(name);
            if (eventDispatcher == null) {
                eventDispatcher = new EventDispatcher(name);
                dispatchers.put(name, eventDispatcher);
            }
            return eventDispatcher;
        }
    }

    public void subscribe(EventListener eventListener, EventProvider eventProvider) {
        synchronized (providers) {
            providers.add(eventProvider);
            eventProvider.addListener(eventListener);
        }
    }

    public void unsubscribe(EventListener eventListener, EventProvider eventProvider) {
        synchronized (providers) {
            eventProvider.removeListener(eventListener);
        }
    }

    public void clear() {
        synchronized (providers) {
            for (EventProvider provider : providers) {
                provider.clear();
            }
            providers.clear();
        }
    }
}
